/*
    Copyright (c) 2006-2007 Ivaylo Ivanov

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
*/
package com.avalonsql.core.db.drivers;

import com.avalonsql.core.configs.DriverDefinitionConfig;
import com.avalonsql.core.db.Const;
import com.avalonsql.core.db.Utils;
import com.avalonsql.core.db.objects.api.IDBObject;
import com.avalonsql.core.db.objects.api.IRootObject;
import com.avalonsql.core.db.objects.impl.*;

import java.net.URLClassLoader;
import java.sql.*;
import java.util.*;

public abstract class DBDriver {

    protected Set<String> sqlKeywords = new HashSet<String>();
    protected Set<String> types = new HashSet<String>();
    protected Set<Class<? extends IDBObject>> supportedClasses = new HashSet<Class<? extends IDBObject>>();
    protected Map<String, String> queriesMap = new HashMap<String, String>();

    protected static String NAME = "";

    protected DBDriver(DriverDefinitionConfig driverDefinitionConfig) throws DBDriverInstatiationException {
        this(driverDefinitionConfig, true);
    }

    protected DBDriver(DriverDefinitionConfig driverDefinitionConfig, boolean loadDrivers) throws DBDriverInstatiationException {
        try {
            String jdbcDriverClassName = driverDefinitionConfig.getJDBCDriverClassName();
            Driver driver;
            if (loadDrivers) {
                URLClassLoader classLoader = new URLClassLoader(Utils.readJars(Const.FOLDER_LIB_JDBC));
                driver = (Driver) Class.forName(jdbcDriverClassName, true, classLoader).newInstance();
            } else {
                driver = (Driver) Class.forName(jdbcDriverClassName).newInstance();
            }
            DriverManager.registerDriver(new DriverWrapper(driver));
        } catch (InstantiationException e) {
            throw new DBDriverInstatiationException(e);
        } catch (IllegalAccessException e) {
            throw new DBDriverInstatiationException(e);
        } catch (ClassNotFoundException e) {
            throw new DBDriverInstatiationException(e);
        } catch (SQLException e) {
            throw new DBDriverInstatiationException(e);
        }
        supportedClasses.add(Table.class);
        supportedClasses.add(TableColumn.class);
        supportedClasses.add(IndexKey.class);
        supportedClasses.add(IndexKeyColumn.class);
        supportedClasses.add(PrimaryKey.class);
        supportedClasses.add(PrimaryKeyColumn.class);
        supportedClasses.add(UniqueKey.class);
        supportedClasses.add(UniqueKeyColumn.class);
        supportedClasses.add(Function.class);

        sqlKeywords.add("ABSOLUTE");
        sqlKeywords.add("ACTION ");
        sqlKeywords.add("ADD");
        sqlKeywords.add("ALL");
        sqlKeywords.add("ALLOCATE");
        sqlKeywords.add("ALTER");
        sqlKeywords.add("AND");
        sqlKeywords.add("ANY");
        sqlKeywords.add("ARE");
        sqlKeywords.add("AS");
        sqlKeywords.add("ASC");
        sqlKeywords.add("ASSERTION");
        sqlKeywords.add("AT");
        sqlKeywords.add("AUTHORIZATION");
        sqlKeywords.add("AVG");
        sqlKeywords.add("BEGIN");
        sqlKeywords.add("BETWEEN");
        sqlKeywords.add("BIT");
        sqlKeywords.add("BIT_LENGTH");
        sqlKeywords.add("BOTH");
        sqlKeywords.add("BY");
        sqlKeywords.add("CASCADE");
        sqlKeywords.add("CASCADED");
        sqlKeywords.add("CASE");
        sqlKeywords.add("CAST");
        sqlKeywords.add("CATALOG");
        sqlKeywords.add("CHAR");
        sqlKeywords.add("CHAR_");
        sqlKeywords.add("CHARACTER");
        sqlKeywords.add("CHARACTER_LENGTH");
        sqlKeywords.add("CHECK");
        sqlKeywords.add("CLOSE");
        sqlKeywords.add("COALESCE");
        sqlKeywords.add("COLLATE");
        sqlKeywords.add("COLLATION");
        sqlKeywords.add("COLUMN");
        sqlKeywords.add("COMMIT");
        sqlKeywords.add("CONNECT");
        sqlKeywords.add("CONNECTION");
        sqlKeywords.add("CONSTRAINT");
        sqlKeywords.add("CONSTRAINTS");
        sqlKeywords.add("CONTINUE");
        sqlKeywords.add("CONVERT");
        sqlKeywords.add("CORRESPONDING");
        sqlKeywords.add("COUNT");
        sqlKeywords.add("CREATE");
        sqlKeywords.add("CROSS");
        sqlKeywords.add("CURRENT");
        sqlKeywords.add("CURRENT_");
        sqlKeywords.add("CURRENT_DATE");
        sqlKeywords.add("CURRENT_TIME");
        sqlKeywords.add("CURRENT_TIMESTAMP");
        sqlKeywords.add("CURSOR");
        sqlKeywords.add("DATE");
        sqlKeywords.add("DAY");
        sqlKeywords.add("DEALLOCATE");
        sqlKeywords.add("DEC");
        sqlKeywords.add("DECIMAL");
        sqlKeywords.add("DECLARE");
        sqlKeywords.add("DEFAULT");
        sqlKeywords.add("DEFERRABLE");
        sqlKeywords.add("DEFERRED");
        sqlKeywords.add("DELETE");
        sqlKeywords.add("DESC");
        sqlKeywords.add("DESCRIBE");
        sqlKeywords.add("DESCRIPTOR");
        sqlKeywords.add("DIAGNOSTICS");
        sqlKeywords.add("DISCONNECT");
        sqlKeywords.add("DISTINCT");
        sqlKeywords.add("DOMAIN");
        sqlKeywords.add("DOUBLE");
        sqlKeywords.add("DROP");
        sqlKeywords.add("ELSE");
        sqlKeywords.add("END");
        sqlKeywords.add("END-EXEC");
        sqlKeywords.add("ESCAPE");
        sqlKeywords.add("EXCEPT");
        sqlKeywords.add("EXCEPTION");
        sqlKeywords.add("EXEC");
        sqlKeywords.add("EXECUTE");
        sqlKeywords.add("EXISTS");
        sqlKeywords.add("EXTERNAL");
        sqlKeywords.add("EXTRACT");
        sqlKeywords.add("FALSE");
        sqlKeywords.add("FETCH");
        sqlKeywords.add("FIRST");
        sqlKeywords.add("FLOAT");
        sqlKeywords.add("FOR");
        sqlKeywords.add("FOREIGN");
        sqlKeywords.add("FOUND");
        sqlKeywords.add("FROM");
        sqlKeywords.add("FULL");
        sqlKeywords.add("GET");
        sqlKeywords.add("GLOBAL");
        sqlKeywords.add("GO");
        sqlKeywords.add("GOTO");
        sqlKeywords.add("GRANT");
        sqlKeywords.add("GROUP");
        sqlKeywords.add("HAVING");
        sqlKeywords.add("HOUR");
        sqlKeywords.add("HOUR");
        sqlKeywords.add("IDENTITY");
        sqlKeywords.add("IMMEDIATE");
        sqlKeywords.add("IN");
        sqlKeywords.add("INDICATOR");
        sqlKeywords.add("INITIALLY");
        sqlKeywords.add("INNER");
        sqlKeywords.add("INPUT");
        sqlKeywords.add("INSENSITIVE");
        sqlKeywords.add("INSERT");
        sqlKeywords.add("INT");
        sqlKeywords.add("INTEGER");
        sqlKeywords.add("INTERSECT");
        sqlKeywords.add("INTERVAL");
        sqlKeywords.add("INTO");
        sqlKeywords.add("IS");
        sqlKeywords.add("ISOLATION");
        sqlKeywords.add("JOIN");
        sqlKeywords.add("KEY");
        sqlKeywords.add("LANGUAGE");
        sqlKeywords.add("LAST");
        sqlKeywords.add("LEADING");
        sqlKeywords.add("LEFT");
        sqlKeywords.add("LENGTH");
        sqlKeywords.add("LEVEL");
        sqlKeywords.add("LIKE");
        sqlKeywords.add("LOCAL");
        sqlKeywords.add("LOWER");
        sqlKeywords.add("MATCH");
        sqlKeywords.add("MAX");
        sqlKeywords.add("MIN");
        sqlKeywords.add("MINUTE");
        sqlKeywords.add("MODULE");
        sqlKeywords.add("MONTH");
        sqlKeywords.add("NAMES");
        sqlKeywords.add("NATIONAL");
        sqlKeywords.add("NATURAL");
        sqlKeywords.add("NCHAR");
        sqlKeywords.add("NEXT");
        sqlKeywords.add("NO");
        sqlKeywords.add("NOT");
        sqlKeywords.add("NULL");
        sqlKeywords.add("NULLIF");
        sqlKeywords.add("NUMERIC");
        sqlKeywords.add("OCTET_LENGTH");
        sqlKeywords.add("OF");
        sqlKeywords.add("ON");
        sqlKeywords.add("ONLY");
        sqlKeywords.add("OPEN");
        sqlKeywords.add("OPTION");
        sqlKeywords.add("OR");
        sqlKeywords.add("ORDER");
        sqlKeywords.add("OUTER");
        sqlKeywords.add("OUTPUT");
        sqlKeywords.add("OVERLAPS");
        sqlKeywords.add("PAD");
        sqlKeywords.add("PARTIAL");
        sqlKeywords.add("POSITION");
        sqlKeywords.add("PRECISION");
        sqlKeywords.add("PREPARE");
        sqlKeywords.add("PRESERVE");
        sqlKeywords.add("PRIMARY");
        sqlKeywords.add("PRIOR");
        sqlKeywords.add("PRIVILEGES");
        sqlKeywords.add("PROCEDURE");
        sqlKeywords.add("PUBLIC");
        sqlKeywords.add("READ");
        sqlKeywords.add("REAL");
        sqlKeywords.add("REFERENCES");
        sqlKeywords.add("RELATIVE");
        sqlKeywords.add("RESTRICT");
        sqlKeywords.add("REVOKE");
        sqlKeywords.add("RIGHT");
        sqlKeywords.add("ROLLBACK");
        sqlKeywords.add("ROWS");
        sqlKeywords.add("SCHEMA");
        sqlKeywords.add("SCROLL");
        sqlKeywords.add("SECOND");
        sqlKeywords.add("SECTION");
        sqlKeywords.add("SELECT");
        sqlKeywords.add("SESSION");
        sqlKeywords.add("SESSION_");
        sqlKeywords.add("SET");
        sqlKeywords.add("SIZE");
        sqlKeywords.add("SMALLINT");
        sqlKeywords.add("SOME");
        sqlKeywords.add("SPACE");
        sqlKeywords.add("SQL");
        sqlKeywords.add("SQLCODE");
        sqlKeywords.add("SQLERROR");
        sqlKeywords.add("SQLSTATE");
        sqlKeywords.add("SUBSTRING");
        sqlKeywords.add("SUM");
        sqlKeywords.add("SYSTEM_USER");
        sqlKeywords.add("TABLE");
        sqlKeywords.add("TEMPORARY");
        sqlKeywords.add("THEN");
        sqlKeywords.add("TIME");
        sqlKeywords.add("TIMESTAMP");
        sqlKeywords.add("TIMEZONE_");
        sqlKeywords.add("TIMEZONE_MINUTE");
        sqlKeywords.add("TO");
        sqlKeywords.add("TRAILING");
        sqlKeywords.add("TRANSACTION");
        sqlKeywords.add("TRANSLATE");
        sqlKeywords.add("TRANSLATION");
        sqlKeywords.add("TRIM");
        sqlKeywords.add("TRUE");
        sqlKeywords.add("UNION");
        sqlKeywords.add("UNIQUE");
        sqlKeywords.add("UNKNOWN");
        sqlKeywords.add("UPDATE");
        sqlKeywords.add("UPPER");
        sqlKeywords.add("USAGE");
        sqlKeywords.add("USER");
        sqlKeywords.add("USER");
        sqlKeywords.add("USER");
        sqlKeywords.add("USING");
        sqlKeywords.add("VALUE");
        sqlKeywords.add("VALUES");
        sqlKeywords.add("VARCHAR");
        sqlKeywords.add("VARYING");
        sqlKeywords.add("VIEW");
        sqlKeywords.add("WHEN");
        sqlKeywords.add("WHENEVER");
        sqlKeywords.add("WHERE");
        sqlKeywords.add("WITH");
        sqlKeywords.add("WORK");
        sqlKeywords.add("WRITE");
        sqlKeywords.add("YEAR");
        sqlKeywords.add("ZONE");
    }

    public String getName() {
        return NAME;
    }

    public Set<String> getSQLKeywords() {
        return sqlKeywords;
    }

    public Set<String> getTypes() {
        return types;
    }

    public String getQuery(String key) {
        return queriesMap.get(key);
    }

    public abstract Class<? extends IRootObject> getRootObjectClass();

    public Class<? extends IRootObject> getDatabaseRootObjectClass() {
        return getRootObjectClass();
    }

    public boolean supports(Class<? extends DBObject> className) {
        return supportedClasses.contains(className);
    }

    protected class DriverWrapper implements Driver {

        protected Driver driver;

        protected DriverWrapper(Driver driver) {
            this.driver = driver;
        }

        public Connection connect(String url, Properties info) throws SQLException {
            return driver.connect(url, info);
        }

        public boolean acceptsURL(String url) throws SQLException {
            return driver.acceptsURL(url);
        }

        public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
            return driver.getPropertyInfo(url, info);
        }

        public int getMajorVersion() {
            return driver.getMajorVersion();
        }

        public int getMinorVersion() {
            return driver.getMinorVersion();
        }

        public boolean jdbcCompliant() {
            return driver.jdbcCompliant();
        }
    }

}
